package com.xrtn.controller;

import com.xrtn.bean.*;
import com.xrtn.page.Page;
import com.xrtn.service.ICommonService;
import com.xrtn.service.IDoctorService;
import com.xrtn.service.ISysDoctorService;
import com.xrtn.service.ISysOrderService;
import com.xrtn.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by tu_pei on 2018/3/5.
 */
@Api("患者|病历相关接口")
@Controller
@RequestMapping("/patient")
public class PatientController {

    @Autowired
    private ICommonService commonService;

    @Autowired
    private IDoctorService doctorService;

    @Autowired
    private ISysDoctorService sysDoctorService;
    @Autowired
    private ISysOrderService sysOrderService;

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {

        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }
    /**
     * 进入病历管理患者中心
     * @return
     */
    @RequestMapping(value = "/gotoUserlib",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoUserlib(ModelAndView modelAndView){
        modelAndView.setViewName("userlib");
        return modelAndView;
    }
    /**
     * 进入病历管理患者中心
     * @return
     */
    @RequestMapping(value = "/gotoTreatStat",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoTreatStat(ModelAndView modelAndView){
        modelAndView.setViewName("treatstat");
        return modelAndView;
    }
    /**
     * 进入病历详情
     * @return
     */
    @RequestMapping(value = "/gotoPatientInfo",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoPatientInfo(ModelAndView modelAndView,Integer userId,Integer patientId){
        modelAndView.setViewName("userPatientDetail");
        modelAndView.addObject("userId", userId);
        modelAndView.addObject("patientId", patientId);
        return modelAndView;
    }
    /**
     * 根据用户id查询患者列表
     * @return
     */
    @ApiOperation(value = "根据用户id查询患者列表",notes="根据用户id查询患者列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=false,value="用户id",defaultValue = "1"),
    })
    @RequestMapping(value = "/selectPatientInfoList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectPatientInfoList(Integer userId){

        ResponseData data = new ResponseData();
        List<TPatientInfo> patientList = commonService.selectPatientListByUserId(userId);

        data.setResults(patientList);

        // 返回数据
        return data;
    }

    /**
     * 根据id删除宝宝及相关信息
     * @return
     */
    @ApiOperation(value = "删除宝宝",notes="删除宝宝")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="patientId",dataType="int",required=false,value="宝宝id",defaultValue = "1"),
    })
    @RequestMapping(value = "/deletePatientInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData deletePatientInfo(Integer patientId){

        ResponseData data = new ResponseData();

        Integer status = commonService.deletePatientInfo(patientId);

        switch (status) {
            case 0:{
                data.setCodeEnum(CodeEnum.SUCCESS);
            }
            break;
            case 1:{ // 宝宝不存在
                data.setCodeEnum(CodeEnum.CODE_20007);
            }
            break;
            case 2:{ // 宝宝户已有已完成订单
                data.setCodeEnum(CodeEnum.CODE_20008);
            }
            break;
        }

        data.setResults(status);

        // 返回数据
        return data;
    }

    /**
     * 修改患者病史档案
     * @return
     */
    @ApiOperation(value = "修改患者病史档案",notes="修改患者病史档案")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="patientId",dataType="int",required=true,value="患者id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="justNowHistory",dataType="string",required=false,value="现病史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="allergyHistory",dataType="int",required=false,value="过敏史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userHistory",dataType="string",required=false,value="个人史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="familyHistory",dataType="int",required=false,value="家族史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="vaccineHistory",dataType="int",required=false,value="疫苗接种历史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="laboratoryHistory",dataType="int",required=false,value="实验室辅助检查",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="medicineHistory",dataType="int",required=false,value="用药史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="feverHistory",dataType="int",required=false,value="高烧惊厥史",defaultValue = "1"),

    })
    @RequestMapping(value = "/updatePatientHistory",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData updatePatientHistory(TPatientHistory history, Integer patientId){

        ResponseData data = new ResponseData();

        history.setUserId(patientId);
        commonService.updatePatientHistorySelective(history);

        // 返回数据
        return data;
    }
    /**
     * @Title: selectHistoryTreatmentList
     * @Description: 获取历史病历信息
     * @param @param userId
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "获取历史病历列表",notes="获取历史病历列表")
    @RequestMapping(value = "/selectHistoryTreatmentList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectHistoryTreatmentList(Integer patientId){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 返回数据
        return doctorService.selectHistoryTreatmentList(patientId, data);
    }
    /**
     * 新增患者
     * @return
     */
    @ApiOperation(value = "新增患者",notes="新增患者")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="bookingId",dataType="int",required=false,value="预约单号",defaultValue = "1"),


            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=true,value="预约-用户id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="int",required=false,value="预约-分店id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="doctorId",dataType="int",required=false,value="预约-大夫id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="bookingName",dataType="int",required=false,value="预约-预约人",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="bookingPhone",dataType="int",required=false,value="预约-手机号",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="bookingPhones",dataType="int",required=false,value="预约-手机号",defaultValue = "1"),

            @ApiImplicitParam(paramType="query",name="patientId",dataType="int",required=false,value="患者id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userName",dataType="string",required=true,value="患者姓名",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userImg",dataType="string",required=true,value="患者头像",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userGender",dataType="int",required=true,value="患者性别：0:男;1:女",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userBirthday",dataType="string",required=true,value="生日",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userHeight",dataType="int",required=true,value="身高",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userBodyWeight",dataType="int",required=true,value="体重",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userAddress",dataType="int",required=true,value="地址",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userDesc",dataType="int",required=true,value="备注",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userAge",dataType="int",required=true,value="年龄",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="justNowHistory",dataType="string",required=false,value="现病史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="allergyHistory",dataType="int",required=false,value="过敏史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userHistory",dataType="string",required=false,value="个人史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="familyHistory",dataType="int",required=false,value="家族史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="vaccineHistory",dataType="int",required=false,value="疫苗接种历史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="laboratoryHistory",dataType="int",required=false,value="实验室辅助检查",defaultValue = "1"),
    })
    @RequestMapping(value = "/savePatientInit",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData savePatientInit(TPatientInit patientInit,TBookingInfo bookingInfo, String bookingName,String bookingPhone,
                                        String bookingPhones,
                                        TPatientHistory patientHistory,Integer userId){
        ResponseData data = new ResponseData();
        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{patientInit.getUserName(),
                patientInit.getUserGender(),patientInit.getUserAddress(),patientInit.getUserBirthday(),
                patientInit.getUserBodyWeight(),patientInit.getUserHeight(),patientInit.getUserDesc()});
        if(ObjUtils.isNotEmpty(codeEnum)){
            data.setCodeEnum(CodeEnum.CODE_90001);
            return data;
        }

        try{
            if(ObjUtils.isNotEmpty(patientInit.getUserBirthday())){
                patientInit.setUserAge(DateUtils.getCurrentAgeByBirthdate(patientInit.getUserBirthday()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        Map<String,Object> body = commonService.insertSysTPatientInitSelective(patientInit, bookingInfo,  bookingName, bookingPhone,
                 bookingPhones, patientHistory, userId);

        data.setResults(body);
        // 返回数据
        return data;
    }
    /**
     * @Title: updatePatientInit
     * @Description: 修改基础信息调查表
     * @param @param userId
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "修改基础信息调查表",notes="修改基础信息调查表")
    @RequestMapping(value = "/updatePatientInit",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="bookingId",dataType="int",required=false,value="预约单号",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=true,value="患者姓名",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="patientId",dataType="int",required=false,value="患者id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userName",dataType="string",required=true,value="患者姓名",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userImg",dataType="string",required=true,value="患者头像",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userGender",dataType="int",required=true,value="患者性别：0:男;1:女",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="patientGender",dataType="int",required=true,value="患者性别：0:男;1:女",defaultValue = "1"), // TreeJohn
            @ApiImplicitParam(paramType="query",name="userBirthday",dataType="string",required=true,value="生日",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userHeight",dataType="int",required=true,value="身高",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userBodyWeight",dataType="int",required=true,value="体重",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userAddress",dataType="int",required=true,value="地址",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userDesc",dataType="int",required=true,value="备注",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userAge",dataType="int",required=true,value="年龄",defaultValue = "1"),

            @ApiImplicitParam(paramType="query",name="historyId",dataType="int",required=false,value="病史id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="justNowHistory",dataType="string",required=false,value="现病史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="allergyHistory",dataType="int",required=false,value="过敏史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userHistory",dataType="string",required=false,value="个人史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="familyHistory",dataType="int",required=false,value="家族史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="vaccineHistory",dataType="int",required=false,value="疫苗接种历史",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="laboratoryHistory",dataType="int",required=false,value="实验室辅助检查",defaultValue = "1"),
    })
    @ResponseBody
    public ResponseData updatePatientInit(TPatientInit patientInit, TPatientHistory patientHistory,Integer userId, Integer patientGender,String userScore){

        if (patientInit.getUserGender() == null) {
            patientInit.setUserGender(patientGender); // 特殊处理，前端传的是patientGender
        }

        TPatientInfo patientInfo = new TPatientInfo();
        patientInfo.setUserId(userId);
        patientInfo.setPatientImg(patientInit.getUserImg());
        patientInfo.setPatientName(patientInit.getUserName());
        if (patientInit.getUserGender() == null) {
            patientInfo.setPatientGender(patientGender);
        } else {
            patientInfo.setPatientGender(patientInit.getUserGender());
        }
        patientInfo.setPatientHeight(patientInit.getUserHeight());
        patientInfo.setPatientBodyWeight(patientInit.getUserBodyWeight());
        patientInfo.setPatientBirthday(patientInit.getUserBirthday());
        patientInfo.setPatientAddress(patientInit.getUserAddress());
        patientInfo.setPatientDesc(patientInit.getUserDesc());
        patientInfo.setPatientAge(patientInit.getUserAge());
        patientInfo.setPatientId(patientInit.getPatientId());

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 调用Service

        try{
            if(ObjUtils.isNotEmpty(patientInfo.getPatientBirthday())){
                patientInfo.setPatientAge(DateUtils.getCurrentAgeByBirthdate(patientInfo.getPatientBirthday()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        int count = commonService.updateTPatientInfoSelective(patientInfo);
        if(count < 0 ){
            data.setCodeEnum(CodeEnum.CODE_20002);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("patientId", patientInfo.getPatientId());
        Map<String, Object> patientMap = commonService.selectPatientInitMap(params);
        patientInit.setRelId(Integer.parseInt(patientMap.get("relId").toString()));
        patientInit.setPatientId(patientInfo.getPatientId());
        patientInit.setUserName(patientInfo.getPatientName());
        patientInit.setUserHeight(patientInfo.getPatientHeight());
        patientInit.setUserBodyWeight(patientInfo.getPatientBodyWeight());
        patientInit.setUserBirthday(patientInfo.getPatientBirthday());
        patientInit.setUserAge(patientInfo.getPatientAge());
        patientInit.setUserGender(patientInfo.getPatientGender());
        patientInit.setUserDesc(patientInit.getUserDesc());
        count = commonService.updateTPatientInitSelective(patientInit);

        if(ObjUtils.isNotEmpty(patientInfo.getPatientId())){
            TPatientHistory history = commonService.selectPatientHistoryByPatientId(patientInfo.getPatientId());
            if(ObjUtils.isNotEmpty(history)){
                patientHistory.setUserId(patientInfo.getPatientId());
                count += commonService.updatePatientHistorySelective(patientHistory);
            }else{
                history = new TPatientHistory();
                history.setAllergyHistory(patientHistory.getAllergyHistory());
                history.setFamilyHistory(patientHistory.getFamilyHistory());
                history.setJustNowHistory(patientHistory.getJustNowHistory());
                history.setVaccineHistory(patientHistory.getVaccineHistory());
                history.setUserHistory(patientHistory.getUserHistory());
                history.setLaboratoryHistory(patientHistory.getLaboratoryHistory());
                history.setUserId(patientInfo.getPatientId());
                count += commonService.insertPatientHistorySelective(history);
            }
        }

        if(count < 0){
            data.setCodeEnum(CodeEnum.CODE_50002);
            return data;
        }

        // 返回数据
        return data;
    }
    /**
     * 根据患者id查询基础信息表
     * @return
     */
    @ApiOperation(value = "根据患者id查询基础信息表",notes="根据患者id查询基础信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="patientId",dataType="int",required=false,value="患者Id",defaultValue = "1"),
    })
    @RequestMapping(value = "/selectPatientInit",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectPatientInit(Integer patientId,Integer bookingId){

        ResponseData data = new ResponseData();

        Map<String,Object> params = new HashMap<>();
        params.put("patientId",patientId);
        params.put("bookingId",bookingId);

        Map<String,Object> retMap = new HashMap<>();

        //历史病历
        List<Map<String,Object>> treatmentList = commonService.selectPatientTreatmentList(patientId);
        retMap.put("treatmentList", treatmentList);
        params.put("bookingId",null);

        //基础信息表
        Map<String,Object> patientInit = commonService.selectTPatientInitByMap(params);
        retMap.put("patientInit", patientInit);
        //病历档案
        TPatientHistory patientHistory = commonService.selectPatientHistoryByPatientId(patientId);
        retMap.put("patientHistory", patientHistory);
        //就诊记录
//        params.put("orderState", 0 );
//        Page page = Page.newBuilder(1, 100);
//        Page orderPage = sysOrderService.selectOrderList(page,params);
//        retMap.put("orderList", orderPage.getItems());

        List<TUserNersingRel> nersingList = commonService.selectHomeNursingList(patientId);

        retMap.put("nursingDate", nersingList.size() > 0 ?nersingList.get(0).getCreateTime():null);

        retMap.put("nursingList", nersingList);

        data.setResults(retMap);

        // 返回数据
        return data;
    }

    /**
     * @Title: 查询就诊列表
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "查询就诊列表",notes="查询就诊列表")
    @RequestMapping(value = "/selectPatientList",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="patientId",dataType="string",required=false,value="患者id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="startDate",dataType="string",required=false,value="开始时间",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="endDate",dataType="string",required=false,value="结束时间",defaultValue = "1"),
    })
    @ResponseBody
    public ResponseData selectPatientList(HttpServletRequest request,Integer patientId,String startDate,String endDate){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 调用Service
        Map<String,Object> params = new HashMap<>();

        params.put("patientId",patientId);
        if(ObjUtils.isNotEmpty(startDate)){
            params.put("startDate",startDate+" 00:00:00");
        }
        if(ObjUtils.isNotEmpty(endDate)){
            params.put("endDate",endDate+" 23:59:59");
        }

        List<Map<String,Object>> patientList = commonService.selectPatientList(params);

        data.setResults(patientList);

        // 返回数据
        return data;
    }
    /**
     * @Title: 查询家庭护理表
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "查询家庭护理表",notes="查询家庭护理表")
    @RequestMapping(value = "/selectHomeNursingList",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="bookingId",dataType="int",required=false,value="预约id",defaultValue = "1"),
    })
    @ResponseBody
    public ResponseData selectHomeNursingList(Integer bookingId){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 调用Service

        List<TUserNersingRel> patientList = commonService.selectHomeNursingList(bookingId);

        data.setResults(patientList);

        // 返回数据
        return data;
    }
    /**
     * @Title: saveTreatmentInfo
     * @Description: 保存患者病历详情
     * @param @param userId
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "保存患者病历详情",notes="保存患者病历详情")
    @RequestMapping(value = "/saveTreatmentInfo",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="treatmentId",dataType="int",required=false,value="病历id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=true,value="用户id(家长id)",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="patientId",dataType="int",required=true,value="患者id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="bookingId",dataType="int",required=true,value="预约id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="diseaseTime",dataType="string",required=true,value="发病时间",defaultValue = "2018-03-02"),
            @ApiImplicitParam(paramType="query",name="diseaseInfo",dataType="string",required=true,value="主诉",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="treatmentInit",dataType="string",required=true,value="初步就诊",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="treatmentOpinion",dataType="string",required=true,value="治疗意见",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="treatmentRemarks",dataType="string",required=true,value="备注",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="treatmentImg",dataType="string",required=true,value="舌苔图片",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="pointArray",dataType="string",required=true,value="穴位多选数组,userId:家长ID，diseaseId：穴位id，typeId:类型id（如：头部）",defaultValue = "[{\"userId\":1,\"bookingId\":1,\"patientId\":1,\"doctorId\":1,\"typeId\":1,\"pointId\":1,\"typeName\":111,\"pointName\":123}]"),
            @ApiImplicitParam(paramType="query",name="diseaseArray",dataType="string",required=true,value="病症多选数组(主症和兼症)，userId:家长ID，pointId：病症程度id，typeId:类型id（如：咳嗽）",defaultValue = "[{\"userId\":1,\"bookingId\":1,\"patientId\":1,\"doctorId\":1,\"typeId\":1,\"diseaseId\":1,\"typeName\":111,\"diseaseName\":123}]"),
            @ApiImplicitParam(paramType="query",name="conclusionArray",dataType="string",required=true,value="诊断结论：",defaultValue="[{\"userId\":1,\"bookingId\":1,\"patientId\":1,\"doctorId\":1,\"conclusionId\":1,\"conclusionName\":1}]"),
            @ApiImplicitParam(paramType="query",name="infoIds",dataType="string",value="特病选项ids：",defaultValue="[1,2]"),
            @ApiImplicitParam(paramType="query",name="specialId",dataType="int",value="特病id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="checkResult",dataType="int",value="预估评分结果",defaultValue = "0"),
            @ApiImplicitParam(paramType="query",name="realResult",dataType="int",value="鼻腔镜检查结果",defaultValue = "0"),
            @ApiImplicitParam(paramType="query",name="error",dataType="int",value="误差",defaultValue = "0"),
    })
    @ResponseBody
    public ResponseData saveTreatmentInfo(TPatientTreatment patientTreatments ,String pointArray,String diseaseArray,String conclusionArray,
                                          String infoIds,Integer specialId, Integer checkResult, Integer realResult, Integer error,
                                          String bookingName,String bookingPhone,String bookingPhones,Integer doctorId,Integer subclinicId){
        ResponseData data = new ResponseData();
        //空校验
        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{patientTreatments.getBookingId(),
                patientTreatments.getPatientId(),patientTreatments.getDiseaseInfo(),patientTreatments.getUserId(),
                patientTreatments.getTreatmentInit(),patientTreatments.getTreatmentOpinion(),patientTreatments.getTreatmentRemarks(),
                patientTreatments.getTreatmentImg(),pointArray,diseaseArray});
        if(ObjUtils.isNotEmpty(codeEnum)){
            data.setCodeEnum(codeEnum);
            return data;
        }
        Integer result = 0;
        patientTreatments.setTreatmentTime(new Date());
        if( ObjUtils.isEmpty(patientTreatments.getTreatmentId())){
            // 判断是否有形同预约id，相同患者id的病历，如果有，就不创建了，预约和病历1对1
            String code = doctorService.selectTreatmentInfo(patientTreatments.getBookingId(), patientTreatments.getPatientId()).getCode();
            if (!"20005".equals(code))  {
                data.setCodeEnum(CodeEnum.CODE_20006);
                return data;
            }
            result = doctorService.saveTreatmentInfo(patientTreatments , bookingName, bookingPhone, bookingPhones,
                    doctorId, subclinicId, pointArray, diseaseArray, conclusionArray, infoIds, specialId, checkResult, realResult, error);
        }else{
            result = doctorService.updateTreatmentInfo(patientTreatments , pointArray, diseaseArray, conclusionArray,
                    infoIds, specialId, checkResult, realResult, error);
            if (result == -2) {
                data.setCodeEnum(CodeEnum.CODE_30013);
                return data;
            }
        }
        data.setResults(result);
        return data;
    }

    /**
     * @Title: selectTreatmentInfo
     * @Description: 获取患者病历详情
     * @param @param userId
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "获取患者病历详情",notes="获取患者病历详情")
    @RequestMapping(value = "/selectSysTreatmentInfo",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectTreatmentInfo(Integer patientId,Integer treatmentId,Integer isOld,Integer bookingId){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 返回数据
        return doctorService.selectSysTreatmentInfo(patientId,treatmentId ,isOld,bookingId);
    }
    /**
     * @Title: selectDiseaseBook
     * @Description: 病例统计看板
     * @param @param userId
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "病例统计看板",notes="病例统计看板")
    @RequestMapping(value = "/selectDiseaseBook",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectDiseaseBook(Integer subclinicId,String startTime,String endTime){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 返回数据
        Map<String,Object> params = new HashMap<>();
        params.put("subclinicId", subclinicId);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        return sysDoctorService.selectDiseaseBook(params);
    }
    /**
     * @Title: selectSysPatientList
     * @Description: 获取患者列表
     * @param @param userId
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "获取患者列表",notes="获取患者列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userPhone",dataType="int",required=false,value="手机号",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="timeType",dataType="int",required=false,value="时间分类：0，1，2，3，4：全部，一，二，三，超过三个月未到店",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="payCount",dataType="int",required=false,value="就诊次数：0，1，2，3，4：全部，一，三，五，超过五次以内，",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="levelType",dataType="int",required=false,value="会员等级：0，1，2，3，4，：全部，普通，白银，黄金，铂金h会员",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="string",required=false,value="分店id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="numberStart",dataType="int",required=false,value="下限就诊次数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="numberEnd",dataType="int",required=false,value="上限就诊次数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="page",dataType="string",required=false,value="当前页数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="limit",dataType="string",required=false,value="显示多少条记录",defaultValue = "10"),
            @ApiImplicitParam(paramType="query",name="fromPage",dataType="string",required=false,value="从哪个页面请求",defaultValue = "0"),
    })
    @RequestMapping(value = "/selectSysPatientList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectSysPatientList(HttpServletRequest request, String userPhone,Integer timeType,Integer payCount,Integer levelType, String fromPage,
                                             Integer subclinicId,Integer page, Integer limit,Integer numberStart,Integer numberEnd){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 返回数据
        Map<String,Object> params = new HashMap<>();
        params.put("userPhone",userPhone);
        params.put("timeType",timeType);
        params.put("payCount",payCount);
        params.put("levelType",levelType);
        params.put("subclinicId",subclinicId);
        params.put("numberStart",numberStart);
        params.put("numberEnd",numberEnd);
        params.put("fromPage",fromPage);
//        if(ObjUtils.isEmpty(numberEnd) && ObjUtils.isEmpty(numberStart)){
//            params.put("numberStart",null);
//            params.put("numberEnd",null);
//        }else{
//
//            if(numberEnd > 1){
//                params.put("numberEnd",numberEnd);
//            }
//            if(numberEnd == 1 && numberStart == 1){
//                params.put("numberStart",null);
//                params.put("numberEnd",null);
//            }
//        }

        if ("0".equals(fromPage)) { // 从宝宝库查询
            SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);
            params.put("loginUser",userInfo);
        }

        page = page == null ? 1 : page;
        limit = limit == null ? Integer.MAX_VALUE : limit;
        Page pages = Page.newBuilder(page, limit);

        Page patientList = sysDoctorService.selectSysPatientPageList(pages,params);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("rows", patientList.getItems());
        map.put("records", patientList.getTotalRecord());
        map.put("total", patientList.getTotalPage());
        map.put("page", patientList.getPageNo());
        data.setResults(map);

        return data;
    }
    /**
     * @Title: saveDiseaseList
     * @Description: 新增调查记录
     * @param @param userId
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "新增调查记录",notes="新增调查记录")
    @RequestMapping(value = "/saveDiseaseList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="diseaseArray",dataType="string",required=true,value="数组",defaultValue = "[{\"treatmentId\": 1,\"bookingId\": 1,\"userId\": 1,\"patientId\": 1,\"doctorId\": 1,\"typeId\": 1,\"diseaseId\": 1,\"diseaseName\": \"123\",\"diseaseScore\": 3,\"typeName\":\"1\"}]"),
            @ApiImplicitParam(paramType="query",name="treatmentId",dataType="int",required=false,value="病历id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="bookingId",dataType="string",required=false,value="预约id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userId",dataType="string",required=false,value="用户id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="patientId",dataType="int",required=false,value="患者id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="doctorId",dataType="int",required=false,value="医生id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="typeId",dataType="int",required=false,value="病症类型id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="typeName",dataType="int",required=false,value="病症类型id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="diseaseId",dataType="int",required=false,value="病症id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="diseaseName",dataType="string",required=false,value="病症描述",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="diseaseScore",dataType="string",required=false,value="分值",defaultValue = "1"),
    })
    @ResponseBody
    public ResponseData saveDiseaseList(String diseaseArray){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 调用Service
        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{diseaseArray});

        if(ObjUtils.isNotEmpty(codeEnum)){
            data.setCodeEnum(codeEnum);
            return data;
        }

        int count = commonService.saveDiseaseList(diseaseArray);

        if(count < 0 ){
            data.setCodeEnum(CodeEnum.CODE_6);
            return data;
        }

        // 返回数据
        return data;
    }



    /**
     * @Title: selectPatient
     * @Description: 查询患者列表
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "查询患者列表",notes="查询患者列表")
    @RequestMapping(value = "/selectPatient",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="patientName",dataType="string",required=true,value="患者姓名",defaultValue = "11"),
            @ApiImplicitParam(paramType="query",name="userPhone",dataType="int",required=false,value="用户手机号",defaultValue = "1"),
    })
    @ResponseBody
    public ResponseData selectPatient(String patientName,String userPhone){

        // 创建响应Model
        ResponseData data = new ResponseData();
        // 调用Service

        Map<String,Object> params = new HashMap<>();
        params.put("userPhone", userPhone);
        params.put("patientName", patientName);

        List<TPatientInfo> patinetList = commonService.selectPatient(params);

        data.setResults(patinetList);
        // 返回数据
        return data;
    }

    /**
     * 修改特病选项
     *
     * @return
     */
    @ApiOperation(value = "提交特病选项", notes = "提交特病选项")
    @RequestMapping(value = "/saveSpecialScore", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData saveSpecialScore(Integer treatmentId, Integer specialId, Integer checkResult, Integer realResult, Integer error) {
        ResponseData responseData = new ResponseData();
        if (null == treatmentId || treatmentId == 0){
            responseData.setCodeEnum(CodeEnum.CODE_90001);
            return responseData;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("specialId", specialId);
        hashMap.put("specialCheckScore", checkResult);
        hashMap.put("specialRealScore", realResult);
        hashMap.put("specialError", error);
        hashMap.put("treatmentId", treatmentId);
        doctorService.updateByTreatmentId(hashMap);

        return responseData;
    }
}
